package com.campus.help.controller;

import com.campus.help.common.Result;
import com.campus.help.service.ApplicationService;
import com.campus.help.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 申请记录控制器
 *
 * @author campus-help
 * @since 2025-09-18
 */
@Slf4j
@RestController
@RequestMapping("/application")
public class ApplicationController {

    @Autowired
    private ApplicationService applicationService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取我的申请记录
     */
    @GetMapping("/records")
    public Result<Map<String, Object>> getApplicationRecords(
            @RequestParam(required = false) String status,
            HttpServletRequest request) {
        try {
            // 从token中获取学生ID
            String token = getTokenFromRequest(request);
            Long studentId = jwtUtils.getStudentIdFromToken(token);
            
            Map<String, Object> result = applicationService.getApplicationRecords(studentId, status);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取申请记录失败", e);
            return Result.error("获取申请记录失败: " + e.getMessage());
        }
    }

    /**
     * 取消申请
     */
    @PostMapping("/cancel")
    public Result<String> cancelApplication(
            @RequestBody Map<String, Object> requestData,
            HttpServletRequest request) {
        try {
            // 从token中获取学生ID
            String token = getTokenFromRequest(request);
            Long studentId = jwtUtils.getStudentIdFromToken(token);
            
            Long applicationId = Long.valueOf(requestData.get("applicationId").toString());
            String applicationType = requestData.get("applicationType").toString();
            
            applicationService.cancelApplication(studentId, applicationId, applicationType);
            return Result.success("申请已取消");
        } catch (Exception e) {
            log.error("取消申请失败", e);
            return Result.error("取消申请失败: " + e.getMessage());
        }
    }

    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer ")) {
            return authorization.substring(7);
        }
        throw new RuntimeException("Token不能为空");
    }
}
